package com.flex.mobile.manager;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.flex.mobile.constant.OrderToDriverConst;
import com.flex.mobile.dao.impl.DriverInfoDao;
import com.flex.mobile.dao.impl.DriverOrderDao;
import com.flex.mobile.dao.impl.UserStatusDao;
import com.flex.mobile.dao.model.DriverInfo;
import com.flex.mobile.dao.model.Extent;
import com.flex.mobile.model.Address;
import com.flex.mobile.model.Location;
import com.flex.mobile.model.TaxiOrder;
@Service("driverManager")
public class DriverManager {
	private DriverInfoDao driverInfoDao;
	private UserStatusDao userStatusDao;

	@Autowired
	public void setDriverInfoDao(DriverInfoDao driverInfoDao) {
		this.driverInfoDao = driverInfoDao;
	}

	@Autowired
	public void setUserStatusDao(UserStatusDao userStatusDao) {
		this.userStatusDao = userStatusDao;
	}

	public List<DriverInfo> findDriverInBuffer(TaxiOrder order) {
		List<DriverInfo> driverList = driverInfoDao.findAll();
		for (DriverInfo driver : driverList) {
			driver.setUserStatus(userStatusDao.findByTId(driver.getTid()));
		}
		return filterDriver(driverList,order);
	}

	private List<DriverInfo> filterDriver(List<DriverInfo> driverList, TaxiOrder order) {
		if (driverList.size() < OrderToDriverConst.EACH_DRIVER_COUNT) {
			return driverList;
		} else {
			Address address = order.getStartAddress();
			Location location = address.getLocation();
			Extent extent = Extent.getExtentByTolerance(location, OrderToDriverConst.FIND_DRIVER_BUFFER);
			// 遍历循环，所有的出租车，选出在此范围内的司机
			for (Iterator iterator = driverList.iterator(); iterator.hasNext();) {
				DriverInfo driver = (DriverInfo) iterator.next();
				if (null != driver.getUserStatus()) {
					if (driver.getUserStatus().getLongitude() > 0 && driver.getUserStatus().getLatitude() > 0) {
						Location target = new Location(driver.getUserStatus().getLongitude(), driver.getUserStatus().getLatitude());
						if (!extent.contains(target)) {
							iterator.remove();
						}
					}
				}
				
			}
			filterDriver(driverList, order);
		}
		return null;
	}
}
